/**
 * 
 */
package logic;

import java.util.ArrayList;
import java.util.List;

import persistence.DBCommonAlter;

import jpa_objects.Branch;
import jpa_objects.Business;
import jpa_objects.Business_type;
import jpa_objects.City;
import jpa_objects.Sport;
import json_objects_received.JaxBranch;
import json_objects_received.JaxSport;
import json_objects_send.JSON_Branch;
import json_objects_send.JSON_business;

/**
 * @author Alejandro Casas
 *
 */
public class CluvieBusiness {


	/**
	 * 
	 */
	public CluvieBusiness() {
		super();

	}

	public JSON_business registerBusiness(String name, String type,
			String mail, String password, List<JaxBranch> branchlist) {
		java.sql.Timestamp t=new java.sql.Timestamp(new java.util.Date().getTime());
		try {

			Business b=new Business("", branchlist.get(0).getCountry(),"",""+t, mail,"", name, 0,RSA.encryptString(password),
					branchlist.get(0).getPhone(), "", 0, "", new Business_type(type),
					new City(branchlist.get(0).getCity(), branchlist.get(0).getCountry()),
					convertBranchList(branchlist,mail),getSportsOfInterest(branchlist));


			new DBCommonAlter().saveUser(b, DBCommonAlter.SAVE_USER);
			return new JSON_business(name, convertBranchListToJSON(branchlist,mail), type, false, mail, 0);
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}
	}

	private List<Sport> getSportsOfInterest(List<JaxBranch> branchlist) {

		List<Sport> r=new ArrayList<Sport>();
		for (JaxBranch b : branchlist) {
			for (JaxSport s : b.getSports()) {
				r.add(new Sport(s.getName(), s.getWraper()));
			}
		}
		return r;
	}

	private List<JSON_Branch> convertBranchListToJSON(List<JaxBranch> branchlist,String mailBusiness) {

		List<JSON_Branch> r=new ArrayList<JSON_Branch>();
		for (JaxBranch b : branchlist) {
			r.add(new JSON_Branch(b.getName(), b.getAddress(), b.getCountry(), b.getOpeningHours(),
					b.getMail(), b.getPhone(), mailBusiness, b.getCity(), b.getLat(), b.getLng(),
					convertJaxSportToString(b.getSports())));
		}
		return r;
	}

	private List<String> convertJaxSportToString(List<JaxSport> sports) {
		List<String> r=new ArrayList<String>();
		for (JaxSport s : sports) {
			r.add(s.getName()+"/"+s.getWraper());
		}
		return r;

	}

	private List<Branch> convertBranchList(List<JaxBranch> branchlist,String mailBusiness) {
		List<Branch> r=new ArrayList<Branch>();
		for (JaxBranch b : branchlist) {
			r.add(new Branch(b.getName(), b.getAddress(), b.getCountry(), b.getOpeningHours(),
					b.getMail(), b.getPhone(),
					mailBusiness, new City(b.getCity(),b.getCountry()), b.getLat(), b.getLng()));
		}
		return r;
	}

}
